const https = require('https');
//引入helper
const help = require('./Helper');
//引入雪花算法生成id
const Snowflake = require('./snowflake')
//引入date生成时间
const dateFormat = require('./date')


module.exports = function (app) {

    app.use('/wx', loginRouter)

    //登录拦截中间件
    function loginRouter(req, res, next) {
        let token = req.headers.token
        if (token) {
            help(`select * from session where id = ${token}`).then(ret => {
                if (ret.length) {
                    let session = ret[0]
                    req.session = {
                        userId: session.userId,
                        userName: session.userName
                    }
                    next()
                } else {
                    res.status(406).send({ errorMsg: '当前用户未登录' })
                }
            })
        } else {
            res.status(405).send({ errorMsg: '缺少token,请先进行登录' })
        }
    }

    //获取用户信息
    app.get('/wxlogin', (req, res, next) => {
        let appid = 'wx58ddfe3723376d7c'
        let secret = '6f16f047529bc5cc5a550be7c0ff1552'
        let code = req.query.code
        https.get(`https://api.weixin.qq.com/sns/jscode2session?appid=${appid}&secret=${secret}&js_code=${code}&grant_type=authorization_code`, (ret) => {
            ret.on('data', (ret) => {
                ret = JSON.parse(ret.toString())
                //存储openid
                let openid = ret.openid
                if (!openid) {
                    res.send('获取错误')
                }
                //如果查询到了
                else {
                    //查询是否存在openid语句
                    let queryMember = `select * from member where openId = '${openid}'`
                    let insert = `INSERT INTO member(openId) VALUES('${openid}')`
                    help(queryMember).then(memberRet => {
                        //判断是否已经存在
                        if (memberRet.length) {
                            //将值挂在req中传到下一级
                            req.member = memberRet[0]
                            next()
                        } else {//用户不存在，使用openid注册
                            help(insert).then(newMember => {
                                //注册成功返回信息
                                help(queryMember).then(memberRet => {
                                    //将值挂在req中传到下一级
                                    req.member = memberRet[0]
                                    next()
                                })
                            })
                        }
                    })
                }
            });
        }).on('error', (e) => {
            console.error(e);
        });
    }, (req, res) => {
        let member = req.member
        let token = Snowflake()
        let date = dateFormat()
        help(`
        INSERT INTO session(id,userId,userName,inTime,platform) 
        VALUES(${token},'${member._id}','${member.nickName}','${date}','wx')
        `).then(ret => {
            res.send({
                avatarUrl: member.avatarUrl,
                nickName: member.nickName,
                openId: member.openId,
                _id: member._id,
                token
            })
        })
    })

    //上传用户信息
    app.put('/wx/member', (req, res) => {
        let userInfo = req.body
        console.log(userInfo)
        help(`
        update member
        set nickName = '${userInfo.nickName}',avatarUrl = '${userInfo.avatarUrl}'
        where _id = '${req.session.userId}'
        `).then(ret => {
            res.send(ret)
        })
    })

    //获取地址信息
    app.get('/wx/address', loginRouter, (req, res) => {
        if (req.session.userId) {
            help(`
            select * from address where memberId = ${req.session.userId}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '请传入memberId' })
        }
    })


    //修改地址信息时获取默认地址信息
    //获取地址信息
    app.get('/wx/address/addAddress', (req, res) => {
        console.log(req.query)
        if (req.query.address) {
            help(`
            select * from address where _id = ${req.query.address}
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '请传入address' })
        }
    })

    //新增收货地址
    //receiver 收货人姓名 必填
    //phone 电话号码 必填
    //city 省市区 必填
    //area 详细地址
    app.post('/wx/address', (req, res) => {
        if (req.session.userId && req.body.receiver && req.body.phone && req.body.city) {
            help(`
            INSERT INTO address(memberId,receiver,phone,city,area)
            VALUES('${req.session.userId}','${req.body.receiver}','${req.body.phone}','${req.body.city}','${req.body.area || ''}')
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })

    //修改默认地址
    //address 当前地址id 必填
    //isDefault 是否为默认值
    app.put('/wx/address/default', (req, res) => {
        let address = req.body.address, memberId = req.session.userId, isDefault = req.body.isDefault ? 1 : 0
        if (address && memberId) {
            ///首先先将所有的默认值改为0
            help(`
            update address
            set isDefault = 0
            where memberId = '${memberId}'
            `).then(ret => {
                help(`
                update address
                set isDefault = '${isDefault}'
                where memberId = '${memberId}' and _id = '${address}'
                `)
                res.send(ret)
            })
        } else {
            res.send(errorMsg)
        }
    })

    //删除当前选中项
    //address 当前地址id 必填
    app.delete('/wx/address/delete', (req, res) => {
        let address = req.body.address
        if (address) {
            ///逻辑删除地址信息
            help(`
            update address
            set state = 0
            where _id = '${address}'
            `).then(ret => {
                res.send(ret)
            })
        } else {
            res.send(errorMsg)
        }
    })

    //更新信息
    //addressId 地址_id 必填
    //memberId 用户id 必填
    //receiver 收货人姓名 非必填
    //phone 电话号码 非必填
    //city 省市区 非必填
    //area 详细地址 非必填
    app.put('/wx/address/update', (req, res) => {
        if (req.body.addressId) {
            //需要修改的项
            let updateKey = ['receiver', 'phone', 'city', 'area']
            let updateValue = []
            for (i = 0; i < updateKey.length; i++) {
                let key = updateKey[i], value = req.body[key]
                if (value) updateValue.push(`${key}='${value}'`)
            }
            help(`update address set ${updateValue.join(',')} where _id = '${req.body.addressId}'`).then(ret => {
                res.send(ret)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })



    //分类界面获取分类商品
    //_id---categoryId  category表的_id对应category_product表的categoryId
    //pageSize、pageNum 分页
    //分类列表查询数据
    app.get('/wx/categoryProduct', (req, res) => {
        let pageSize = req.query.pageSize || 5
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let categoryId = req.query._id
        if (categoryId) {
            help(`
            select * from category_product as c
            left join product as p 
            on c.productId = p._id
            where c.categoryId = '${categoryId}'
            limit ${pageSize} offset ${offset} 
            `).then(product => {
                res.send(product)
            })
        } else {
            res.send({ errorMsg: '传入参数错误' })
        }
    })

    //获取首页轮播图
    app.get('/wx/index', (req, res) => {
        let type = req.query.type
        help(`select * from index_region where type = '${type}' and status = 1 and state = 1`).then(ret => {
            res.send(ret)
        })
    })

    //获取首页推荐，分页查询
    //查询首页
    //pageNum  默认为1
    //pageSize 默认为5
    app.get('/wx/getRecommend', (req, res) => {
        let pageSize = req.query.pageSize || 5
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let sqlWhere = `from index_region where type = 'recommend' and state = 1 and status = 1`
        help(`
        select * ${sqlWhere} limit ${pageSize} offset ${offset};
        select count(*) as total ${sqlWhere}
        `).then(ret => {
            res.send(ret ? {
                rows: ret[0],
                total: ret[1][0].total
            } : { errorMsg: '获取数据失败' })
        })
    })

    //获取分类列表
    app.get('/wx/getCategory', (req, res) => {
        help(`select * from category where state = 1`).then(ret => {
            if (res) {
                res.send(ret)
            } else {
                res.send({ errorMsg: '获取数据失败' })
            }
        })
    })

    //获取商品列表
    //
    app.get('/wx/getProduct', (req, res) => {
        let rank = ''
        console.log(req.query)
        let sorted = req.query.sorted ? req.query.sorted : 0
        switch (sorted) {
            case '0':
                break;
            case '1':
                rank = 'order by p.sales desc'
                break;
            case '2':
                rank = 'order by s.originalPrice asc'
                break;
            case '3':
                rank = 'order by s.originalPrice desc'
                break;

            default:
                break;
        }
        let pageSize = req.query.pageSize || 5
        let pageNum = req.query.pageNum || 1
        let offset = (pageNum - 1) * pageSize
        let key = req.query.key
        let brandId = req.query.brandIds
        let sqlWhere = ''
        if (req.query.brandIds) {
            sqlWhere += `and brandId in (${brandId})`
        }
        if (req.query.key) {
            sqlWhere += `and p.name like "%${key}%" or c.name like "%${key}%"`
        }
        help(`
        select 
        p._id as productId,p.imgs as img,p.name as productName,c.name as categoryName,p.sales as sales,s.originalPrice,b.name as brandName
        from product as p
        left join sku as s on p._id = s.productId 
        left join category_product as cp on cp.productId = p._id
        left join category as c on cp.categoryId = c._id
        left join brand as b on p.brandId = b._id
        where p.state = 1 and p.status = 1 ${sqlWhere} ${rank}
        limit ${pageSize} offset ${offset};
        select count(*) as total from product as p
        left join sku as s on p._id = s.productId 
        left join category_product as cp on cp.productId = p._id
        left join category as c on cp.categoryId = c._id
        left join brand as b on p.brandId = b._id
        where p.state = 1 and p.status = 1 ${sqlWhere}
        `).then(ret => {
            res.send(ret ? {
                rows: ret[0],
                total: ret[1][0].total
            } : { errorMsg: '标题不存在' })
        })
    })

    //获取品牌
    app.get('/wx/getBrand', (req, res) => {
        help(`select * from brand where status = 1 and state = 1`).then(ret => {
            if (res) {
                res.send(ret)
            } else {
                res.send({ errorMsg: '获取数据失败' })
            }
        })
    })

    //获取商品详情
    app.get('/wx/detailProduct', (req, res) => {
        let productId = req.query.productId
        let imgs = [];
        help(`
        select s._id,s.props,s.salePrice,s.originalPrice,s.imgs,s.skuSpecification,p.name as productName
        from sku as s
        left join product as p on s.productId = p._id
        where productId = '${productId}' and s.state = 1`).then(ret => {
            for (let i = 0; i < ret.length; i++) {
                imgs.push(ret[i].imgs)
            }
            if (ret) {
                res.send({
                    skus: ret,
                    imgs: imgs
                })
            } else {
                res.send({ errorMsg: '获取数据失败' })
            }
        })
    })

}